package com.mdp.sms.tencent.client;

import com.alibaba.fastjson.JSON;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.utils.LogUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;
import java.util.Random;

/**
 *
 * 腾讯云的短信模板相关的API https://cloud.tencent.com/document/product/382/5817
 * @author lyk
 * @cdate 2019/9/17 15:19
 */
@Service("mdp.sms.utils.smsTemplateApi")
public class SmsTemplateApi {
	@Value("${mdp.sms.appid:1}")
	int appid;
	@Value("${mdp.sms.app-secret:}")
	String appkey;

	static Log log = LogFactory.getLog(SmsTemplateApi.class);

	// 添加短信模板 POST请求
	public static final String addSmsTemplateApi = "https://yun.tim.qq.com/v5/tlssmssvr/add_template?sdkappid=";
	// 修改短信模板 POST请求
	public static final String modifySmsTemplateApi = "https://yun.tim.qq.com/v5/tlssmssvr/mod_template?sdkappid=";
	// 删除短信模板 POST请求
	public static final String delSmsTemplateApi = "https://yun.tim.qq.com/v5/tlssmssvr/del_template?sdkappid=";
	// 短信模板状态查询 POST请求
	public static final String getSmsTemplateApi = "https://yun.tim.qq.com/v5/tlssmssvr/get_template?sdkappid=";

	public Map<String, Object> addSmsTemplate(Map<String, Object> data) {
		String finallyRequestURL=addTimeAndSig(data,addSmsTemplateApi);
		return sentPostRequest(finallyRequestURL, data);
	}
	
	public Map<String, Object> modifySmsTemplate(Map<String, Object> data) {
		String finallyRequestURL=addTimeAndSig(data,modifySmsTemplateApi);
		return sentPostRequest(finallyRequestURL, data);
	}
	
	public Map<String, Object> delSmsTemplate(Map<String, Object> data) {
		String finallyRequestURL=addTimeAndSig(data,delSmsTemplateApi);
		return sentPostRequest(finallyRequestURL, data);
	}

	public Map<String, Object> getSmsTemplate(Map<String, Object> data) {
		String finallyRequestURL=addTimeAndSig(data,getSmsTemplateApi);
		return sentPostRequest(finallyRequestURL, data);
	}

	/**
	 * 为请求的数据添加time和sig
	 */
	public String addTimeAndSig(Map<String, Object> data,String url) {
		// 随机数
		long random = getRandom();
		// 时间
		int time = (int) (System.currentTimeMillis() / 1000);
		String finallyRequestURL =  url+ appid + "&random=" + random;
		StringBuffer buffer = new StringBuffer("appkey=").append(appkey).append("&random=").append(random)
				.append("&time=").append(time);
		String sig = sha256(buffer.toString());
		data.put("time", time);
		data.put("sig", sig);
		return finallyRequestURL;
	}

	/**
	 * 当前时间 UNIX 时间戳
	 */
	public static long getCurrentTime() {
		return System.currentTimeMillis() / 1000;
	}

	/**
	 * 随机数
	 */
	public static long getRandom() {
		return (new Random(SmsTemplateApi.getCurrentTime())).nextInt(900000) + 100000;
	}

	/**
	 * 生成腾讯云的App凭证 sha256（appkey=$appkey&random=$random&time=$time)
	 * appkey这个是访问api的密钥 random这个信息要和请求路径的random参数一致 time表示UNIX 时间戳
	 * @param rawString
	 * @return
	 */
	public static String sha256(String rawString) {
		return DigestUtils.sha256Hex(rawString);
	}

	/**
	 * 发送POST请求 preApi 请求路径 data请求参数 接口调用的结果 result非零表示失败 请求的数据和返回的数据都是需要JSON格式的字符串
	 * unpack error 这个错误可能传的参数有问题  
	 */
	public Map<String, Object> sentPostRequest(String preApi, Map<String, Object> data) {
		String gloNo = MDC.get(LogUtils.GLO_NO_NAME);
		String url = preApi + "&gloNo=" + gloNo;
		log.info("开始调用腾讯云的短信接口" + url);
		ResponseEntity<String> forEntity;
		try {
			RestTemplate restTemplate = new RestTemplate();
			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<Map<String, Object>> requestData = new HttpEntity<Map<String, Object>>(data, requestHeaders);
			forEntity = restTemplate.postForEntity(preApi, requestData, String.class);
		} catch (Exception e) {
			log.error(url + "接口调用异常");
			log.error(e);
			throw new BizException(e.getMessage());
		}
		// 得到返回的json字符串
		String resultStr = forEntity.getBody();
		// json字符串转换成Map对象
		Map<String, Object> resultObject = JSON.parseObject(resultStr, Map.class);
		log.info(url + "接口调用返回结果》》》》》》" + resultObject);
		Integer result = (Integer) resultObject.get("result");
		if (StringUtils.isEmpty(result) || result != 0) {
			String msg = (String) resultObject.get("errmsg");
			log.error("接口返回消息:" + msg);
			Tips tips = new Tips(false, msg);
			if (!StringUtils.isEmpty(msg)) {
				tips.setErrMsg(msg);
			}
			throw new BizException(tips);
		}
		return resultObject;

	}

	public static void main(String[] args) {
		String s="1568809535";
		Number time=(Number)1568809535;
		
		long l=1000L*1568809535;
		System.out.println(new Date(l));
		String[] params= {"123"};
		/*int i = (int) (System.currentTimeMillis() / 1000);
		long l = getRandom();
		StringBuffer buffer = new StringBuffer("appkey=").append("4b0659a2ee8ba4e54a570515fda94aef").append("&random=")
				.append(l).append("&time=").append(i);
		System.out.println(sha256(buffer.toString()));
		System.out.println(i);
		System.out.println(l);*/
	}
}
